<?php

class stuff{
	
	private $units	= array();
	private $stuff	= array();
	private $stuffPos = 5;
	private $key1	= array();
	private $key2	= array();

	private $db	= array();

	public function __construct(&$ary, &$db){
		$this->db	=& $db;
		$this->units($ary);
		$this->update($ary);
	}



	public function update($ary){
		//$this->db->beginTransaction();
		try{
			foreach($ary as $k=>$v){
				$sqls	= $this->parse(&$v);
				//array_walk($sqls, array($this->db, 'exec'));
				$this->db->exec($sqls[0]);
				$this->db->exec($sqls[1]);
			}
		}catch(Exception $e){
			if( $trans ){
				//$this->db->rollBack();
			}
			print_r($e);
			//print_r($sqls);
			die;
		}
		if( $trans ){
			//$this->db->commit();
		}
	}

	public function parse($line){
		$R	= array();
		$fields	= array();
		foreach($line as $k=>$v){
			if( $k < $this->stuffPos ){
				$field		= $this->key1[$k];
				if( $field ){
					$fields[$field]	= $v;
				}
			}else{
				$key	=  $this->key2[$k];
				$R[$key]	= $v;
			}
		}
		$fields['sArray']	= serialize($R);
		foreach($fields as $k=>$v){
			$fields[$k]	= $this->db->quote($v);
		}

		$sql	= "DELETE FROM stuff WHERE 中国饲料号=".$fields['中国饲料号'];
	

		$sql2	= "INSERT INTO stuff (".join(',', array_keys($fields)).") VALUE (".join(',',$fields) .' )';
		return array($sql, $sql2);
	}

	private function units(&$ary){
		$name	= array_shift($ary);
		$code	= array_shift($ary);
		$unit	= array_shift($ary);
		$R	= array();
		foreach($name as $k=>$v){
			if( $code[$k] || $unit[$k]){
				$R[$v]	= array($unit[$k], $code[$k]);
			}
		}
		$R2	= include( D::$user->path().'/units.php' );
		foreach($R2 as $k=>$v){
			if( empty($R[$k]) ){
				$R[$k]	= $v;
			}
		}
		$dir	= D::$user->path();
		if( file_exists( $dir. '/units4.php') ){
			unlink($dir.'/units4.php');
		}
		if( file_exists( $dir. '/units3.php') ){
			rename( $dir.'/units3.php', $dir.'/units4.php');
		}
		if( file_exists( $dir. '/units2.php') ){
			rename( $dir.'/units2.php', $dir.'/units3.php');
		}
		rename( $dir.'/units.php', $dir.'/units2.php');
		file_put_contents(D::$user->path().'/units.php', '<?php return '.var_export($R ,1).'?>');

		$this->units	=& $R;
		$this->parseKey($name);
	}



	
	private function parseKey($arys){
		$maps	= array(
			'饲料名称'	=> '饲料名',
			'饲料描述'	=> '描述'	
		);
		$keys	= array(
				'原料分类',
				'动物种类',
				'饲料名',
				'中国饲料号',
				'单价',
				'配比上限',
				'配比下限',
				'干物质',
				'描述',
				'备注'
			);
		$R	= array();
		$R2	= array();
		foreach($arys as $k=>$v){
			if( $k < $this->stuffPos ){
				$val	= $maps[$v] ? $maps[$v] : $v;
				if(in_array($val, $keys) ){
					$R[$k]	= $val;
				}
			}else{
				$R2[$k]	= $v;
			}
		}
		$this->key1	=& $R;
		$this->key2	=& $R2;
	}








}
?>